<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>测试</title>
  </head>
  <body>
    <button id="btn4">多触发角时函数防抖</button>
    <button id="btn5">多触发角时函数防抖</button>
  </body>
  <script type="text/javascript">
    // 节流与防抖的作用都是防止函数多次调用。
    // 区别在于，假如用户一直触发这个函数，且每次触发函数的间隔小于阙值，防抖的情况下只会调用一次，而节流会每隔一定时间调用函数。
    window.onload = function () {
      // ------------------------------------------
      //不管几个触发事件监听，每隔一段时间只执行一次

      let btn4 = document.getElementById("btn4");
      let btn5 = document.getElementById("btn5");

      //js方法
      document.onkeydown = function (e) {
        var ev = document.all ? window.event : e;
        var keyCode = ev.keyCode || ev.which || ev.charCode;
        if (keyCode == 13) {
          searchFieldInput();
        }
      };
      var save4 = function () {
        console.log("多个事件监听触发仅执行一次[频繁触发]");
      };
      function debounce1(fun, delay) {
        return function (args) {
          let that = this;
          let _args = args;
          clearTimeout(fun.id);
          fun.id = setTimeout(function () {
            fun.call(that, _args);
          }, delay);
        };
      }

      function searchFieldInput() {
        let res = debounce1(save4, 1000);
        res();
      }
      btn4.onclick = searchFieldInput;
      btn5.onclick = searchFieldInput;
    };
  </script>
</html>
